package com.ljkj.blockpay.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.ViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.kongzue.baseokhttp.util.JsonMap;
import com.ljkj.blockpay.R;
import com.ljkj.blockpay.basedata.BaseActivity;
import com.ljkj.blockpay.databinding.ActivityReceiptBinding;
import com.ljkj.blockpay.model.RechargeModel;
import com.ljkj.blockpay.presenter.MainPresenter;
import com.ljkj.blockpay.presenter.ReceiptPresenter;
import com.ljkj.blockpay.presenter.inter.MainInter;
import com.ljkj.blockpay.presenter.inter.ReceiptInter;
import com.ljkj.blockpay.util.BitmapUtil;
import com.ljkj.blockpay.util.ToggleToActivity;
import com.ljkj.blockpay.widget.ClickListener;
import com.ljkj.blockpay.widget.CommonDialog;
import com.ljkj.blockpay.widget.ScreenshotUtil;
import com.luck.picture.lib.tools.ToastUtils;
import com.tbruyelle.rxpermissions3.Permission;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.yxing.ScanCodeConfig;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 收款码页面
 */
public class ReceiptActivity extends BaseActivity<ActivityReceiptBinding, ReceiptPresenter> implements ReceiptInter.ReceiptInterView, ClickListener {

    private String content;
    private String networkType;
    private Bitmap QRbitmap;
    private CommonDialog mSetAmountDialog;
    private EditText etmount;
    private EditText remark;
    private String currencyName;
    private String currencyImg;
    private List<RechargeModel.NetworkDTO> networkList;
    private String currencyMin;
    private String amount;
    private TextView tvunit;
    public static final String[] permissionsGroup =new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    public int initContentView() {
        return R.layout.activity_receipt;
    }

    @Override
    protected ReceiptPresenter createPresenter() {
        return new ReceiptPresenter(this,this);
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected void initData() {
        super.initData();
        binding.setOnClick(this::onClick);
        binding.tvTitle.setTitleContent(R.string.homereceiptcode);
        binding.tvTitle.setTitleColor(R.color.white);
        binding.tvTitle.setLeftBackFinish(this);
        getPresenter().getNetAccuracy();

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_Payment:
                ToggleToActivity.toSelectCurrencyActivity(this, 10);
                break;
            case R.id.tv_setmoney:
                mSetAmountDialog = CommonDialog.Builder.with(ReceiptActivity.this)
                        .setContentView(R.layout.setamount_layout).setOnClickListener(R.id.iv_close, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mSetAmountDialog.dismiss();
                            }
                        })

                        .setOnClickListener(R.id.btn_ok, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                etmount = mSetAmountDialog.findViewById(R.id.et_amount);
                                remark = mSetAmountDialog.findViewById(R.id.et_remark);

                                amount = etmount.getText().toString();
                                binding.tvMoney.setText(currencyName+" "+amount);
                                binding.tvMoney.setVisibility(View.VISIBLE);
                                getPresenter().qrcodeCollect(amount,currencyName);
                                mSetAmountDialog.dismiss();
                            }
                        }).forGravity(Gravity.CENTER).setCancelable(true).setOnKeyListener((dialogInterface, i, keyEvent) -> false).create();
                tvunit = mSetAmountDialog.findViewById(R.id.tv_unit);
                tvunit.setText(currencyName);
                mSetAmountDialog.show();
                break;
            case R.id.tv_savepicture:
                if (currencyImg != null){
                    new RxPermissions(ReceiptActivity.this).requestEachCombined(permissionsGroup).subscribe(new Observer<Permission>() {
                        @Override
                        public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@io.reactivex.rxjava3.annotations.NonNull Permission permission) {
                            savecode();
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
                } else {
                    ToastUtils.s(this,"图片为空不能保存");
                }

                break;

        }
    }

    private void savecode() {


        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                Bitmap bitmap = null;
                try {
                    bitmap = Glide.with(ReceiptActivity.this)
                            .asBitmap()
                            .load(currencyImg)
//                            .load("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic27.nipic.com%2F20130223%2F890845_101648793000_2.jpg&refer=http%3A%2F%2Fpic27.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629286483&t=85b413dca3c8722dea3ce5ca357ad69b")
                            .submit(150, 150).get();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {

                View views = LayoutInflater.from(ReceiptActivity.this).inflate(R.layout.activity_qrcode, null, false);
                ImageView QR = views.findViewById(R.id.iv_qrcq);
                views.findViewById(R.id.iv_userpic);
                views.findViewById(R.id.tv_username);
                views.findViewById(R.id.iv_icon);
                views.findViewById(R.id.tv_unit);
                views.findViewById(R.id.tv_address);
                Glide.with(baseContext).load(currencyImg).into(binding.ivMoneyIcon);

                QRbitmap = ScanCodeConfig.createQRcodeWithLogo(content,bitmap);
                QR.setImageBitmap(QRbitmap);

                Bitmap bitmap3 = createBitmap3(views, getWindow().getDecorView().getWidth(), getWindow().getDecorView().getHeight());
                ScreenshotUtil.saveImageToGallery(bitmap3,ReceiptActivity.this);
            }
        }.execute();

    }
    private static Bitmap bitmap;
    public static Bitmap getBitmap(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;
                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return bitmap;
    }
    public Bitmap createBitmap3(View v, int width, int height) {
        //测量使得view指定大小
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        v.measure(measuredWidth, measuredHeight);
        //调用layout方法布局后，可以得到view的尺寸大小
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        v.draw(c);
        return bmp;
    }

    @Override
    public void qrcodeSuccess(JsonMap jsonMap) {
        content = jsonMap.getString("content");
//
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                Bitmap bitmap = null;
                try {
                    bitmap = Glide.with(ReceiptActivity.this)
                            .asBitmap()
                            .load(currencyImg)
//                            .load("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic27.nipic.com%2F20130223%2F890845_101648793000_2.jpg&refer=http%3A%2F%2Fpic27.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629286483&t=85b413dca3c8722dea3ce5ca357ad69b")
                            .submit(150, 150).get();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                QRbitmap = ScanCodeConfig.createQRCode(content);
                binding.ivScan.setImageBitmap(QRbitmap);
            }
        }.execute();
    }

    @Override
    public void showNetAccuracy(List<RechargeModel> modelList) {

        currencyName = modelList.get(0).getCurrencyName();
        currencyImg = modelList.get(0).getCurrencyImg();
        networkList = modelList.get(0).getNetwork();
        for (int i = 0; i < networkList.size(); i++) {
            currencyMin = networkList.get(0).getCurrencyMin();
            binding.tvNotice.setText(getResources().getString(R.string.money_notice)+currencyName+getResources().getString(R.string.money_notice2)+currencyMin+currencyName+getResources().getString(R.string.money_notice3));
        }
        Glide.with(baseContext).load(currencyImg).into(binding.ivMoneyIcon);
        binding.tvMoneyname.setText(currencyName);
        binding.tvMoney.setText(currencyName);
        getPresenter().qrcodeCollect("",currencyName);

    }

    @Override
    public void collList(List<JsonMap> jsonMapList) {

    }

    @Override
    public void getBitmap(Bitmap bitmap) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 100) {
            return;
        }
        if (data.getExtras() != null) {
            Bundle bundle = data.getExtras();
            JsonMap jsonMap = JsonMap.parse(bundle.getString("jsonMap"));
            switch (requestCode) {
                case 10:
                    currencyName = jsonMap.getString("currencyName");
                    currencyImg = jsonMap.getString("currencyImg");
                    binding.tvMoneyname.setText(currencyName);
                    Glide.with(baseContext).load(currencyImg).into(binding.ivMoneyIcon);
                    binding.tvNotice.setText(getResources().getString(R.string.money_notice)+currencyName+getResources().getString(R.string.money_notice2)+currencyMin+currencyName+getResources().getString(R.string.money_notice3));
                    binding.tvMoney.setText(currencyName);
                    getPresenter().qrcodeCollect(amount,currencyName);
                    break;
                default:
                    break;
            }

        }
    }
}